<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { removeToken } from "@/composables/cookie";
import { showMessage, showModel } from "@/composables/util.js";
import { updatePassword, updateUserInfo } from "@/api/common/user";
import { uploadFile } from "@/api/common/file";
import { findAllCategory, findAllTagByCategoryId, findAllTag } from "@/api/common/common.js";
import { listByTagId, listAllVideoCourses } from "@/api/common/index.js";
import { UserFilled, Search } from "@element-plus/icons-vue";

// 从浏览器本地存储中取出用户信息
let userInfo = JSON.parse(localStorage.getItem("userInfo"))
const router = useRouter()
// 控制个人信息弹出框
let info = ref(false)
let password = ref(false)
let order = ref(false)
let buy = ref(false)
let like = ref(false)
// 设置导航栏激活项
const activeIndex = ref('3')

// 用户表单数据
const form1 = reactive({
  id: null,
  username: null,
  avatar: null,
  token: null
})
const form2 = reactive({
  username: '',
  password: '',
  newPassword: '',
  surePassword: ''
})

// 课程数据
const courseList = ref([])
const total = ref(0)
const title = ref('全部视频课程')

// 分类和标签数据
const categories = ref([])
const tags = ref([])
const hoveredCategoryId = ref(null)
const categoryTags = ref({})

// 搜索和筛选条件
const queryParams = reactive({
  title: '',
  sort: 'newest'
})

onMounted(() => {
  if(userInfo !== null) {
    form1.id = userInfo.id
    form1.username = userInfo.username
    form1.avatar = userInfo.avatar
    form1.token = userInfo.token
    form2.username = userInfo.username
  }
  getAllCategories()
  getAllTags()
  getAllCourses()
})

// 获取所有分类
function getAllCategories() {
  findAllCategory().then((res) => {
    if (res.data.success === true) {
      categories.value = res.data.data
      // 获取每个分类下的标签
      categories.value.forEach(category => {
        getTagsByCategory(category.id)
      })
    }
  })
}

// 获取所有标签
function getAllTags() {
  findAllTag().then((res) => {
    if (res.data.success === true) {
      tags.value = res.data.data
    }
  })
}

// 获取所有视频课程
function getAllCourses() {
  listAllVideoCourses().then((res) => {
    if (res.data.success === true) {
      courseList.value = res.data.data
      total.value = courseList.value.length
    }
  })
}

// 获取指定分类下的标签
function getTagsByCategory(categoryId) {
  findAllTagByCategoryId({ id: categoryId }).then((res) => {
    if (res.data.success === true) {
      categoryTags.value[categoryId] = res.data.data
    }
  })
}

// 分类悬停处理
const handleMouseEnter = (categoryId) => {
  hoveredCategoryId.value = categoryId
}

const handleMouseLeave = () => {
  hoveredCategoryId.value = null
}

// 标签点击处理
function getCourseByTagId(tag) {
  title.value = tag.name
  listByTagId({ id: tag.id, type: 1 }).then((res) => {
    if (res.data.success === true) {
      courseList.value = res.data.data.filter(course => course.type === 1)
      total.value = courseList.value.length
    }
  })
}

// 搜索课程
function searchCourses() {
  if (queryParams.title) {
    const searchTerm = queryParams.title.toLowerCase()
    courseList.value = courseList.value.filter(course => 
      course.title.toLowerCase().includes(searchTerm) || 
      (course.description && course.description.toLowerCase().includes(searchTerm))
    )
    total.value = courseList.value.length
  } else {
    getAllCourses()
  }
}

// 清除搜索
function clearSearch() {
  queryParams.title = ''
  getAllCourses()
}

// 排序处理
function changeSort(sort) {
  queryParams.sort = sort
  if (sort === 'newest') {
    courseList.value.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
  } else if (sort === 'hotest') {
    courseList.value.sort((a, b) => b.watchNums - a.watchNums)
  } else if (sort === 'price') {
    courseList.value.sort((a, b) => a.price - b.price)
  }
}

// 跳转到视频详情页
function goToVideo(id) {
  router.push(`/video/${id}`)
}

// 用户相关方法
const handleAvatarChange = (file) => {
  let formData = new FormData()
  formData.append('file', file.raw)
  uploadFile(formData).then((e) => {
    if (e.data.success == false) {
      showMessage(e.message, 'error')
      return
    }
    form1.avatar = e.data.data
  })
}

const saveInfo = () => {
  updateUserInfo(form1).then((res) => {
    if (res.data.success === true) {
      showMessage('修改成功')
      localStorage.setItem("userInfo", JSON.stringify(res.data.data))
      userInfo = JSON.parse(localStorage.getItem("userInfo"))
      info = false
      window.location.reload()
    } else {
      showMessage(res.data.message, 'error')
    }
  })
}

const savePassword = () => {
  if(form2.newPassword !== form2.surePassword) {
    showMessage('两次密码输入不一致', 'error')
    return
  }
  updatePassword(form2).then((res) => {
    if (res.data.success === true) {
      showMessage('修改成功')
      removeToken()
      localStorage.removeItem('userInfo')
      router.push('/login')
    } else {
      showMessage(res.data.message, 'error')
    }
  })
}

const logout = () => {
  showModel('是否退出登录?').then(() => {
    removeToken()
    localStorage.removeItem('userInfo')
    showMessage('退出登录成功!')
    router.push('/login')
  })
}

function goLogin() {
  router.push('/login')
}

function goOrder() {
  router.push('/order')
}
function goCollect() {
  router.push('/collect')
}
// 价格格式化
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}
</script>

<template>
  <el-container class="home-container">
    <!-- 导航栏 -->
    <el-header class="header">
      <div class="nav-container">
        <div class="logo">
          高校<span class="blue">互联网技术</span>在线学习平台
        </div>
        <el-menu mode="horizontal" :default-active="activeIndex">
          <el-menu-item index="1">
            <router-link to="/">首页</router-link>
          </el-menu-item>
          <el-menu-item index="2">
            <router-link to="/article-course">图文课程</router-link>
          </el-menu-item>
          <el-menu-item index="3">
            <router-link to="/video-course">视频课程</router-link>
          </el-menu-item>
        </el-menu>
        <div class="search-box">
          <el-input v-model="queryParams.title"
                   placeholder="搜索课程..."
                   class="search-input"
                   @keyup.enter="searchCourses"
                   clearable
                   @clear="clearSearch">
            <template #suffix>
              <el-icon class="el-input__icon" @click="searchCourses"><search /></el-icon>
            </template>
          </el-input>
        </div>
        <!-- 未登录状态 -->
        <div class="user-wrapper" v-if="!userInfo">
          <el-button type="primary" class="login-btn" @click="goLogin" round>
            <i class="el-icon-user"></i>
            <span>登录 / 注册</span>
          </el-button>
        </div>

        <!-- 已登录状态 -->
        <div class="user-panel" v-else>
          <el-dropdown trigger="hover">
            <div class="user-card">
              <div class="profile">
                <el-avatar :src="userInfo.avatar" :size="36" class="user-avatar"
                  :style="{ backgroundColor: '#8ac8ff' }" />
              </div>
            </div>

            <!-- 下拉菜单 -->
            <template #dropdown>
              <el-dropdown-menu class="user-menu">
                <el-dropdown-item class="menu-item" @click="info = true">
                  <i class="el-icon-user-solid"></i>个人信息
                </el-dropdown-item>
                <el-dropdown-item class="menu-item" @click="goOrder">
                  <i class="el-icon-time"></i>我的订单
                </el-dropdown-item>
                <el-dropdown-item class="menu-item" @click="goCollect">
                  <i class="el-icon-star-off"></i>我的收藏
                </el-dropdown-item>
                <el-dropdown-item class="menu-item" @click="password = true">
                  <i class="el-icon-lock"></i>修改密码
                </el-dropdown-item>
                <el-dropdown-item class="menu-item logout" @click="logout">
                  <i class="el-icon-switch-button"></i>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <el-main class="main-content">
      <!-- 页面标题和描述 -->
      <div class="page-header video-theme">
        <h1 class="page-title">视频课程</h1>
        <p class="page-description">精品视频教程，让学习更直观有效</p>
      </div>

      <!-- 分类导航区域 -->
      <h2 class="section-title">分类导航</h2>
      <div class="category-container">
        <el-dropdown v-for="category in categories" :key="category.id" 
                    placement="bottom-start" 
                    trigger="hover"
                    @visible-change="visible => visible ? handleMouseEnter(category.id) : handleMouseLeave()">
          <el-button class="category-tag" :class="{ 'active': hoveredCategoryId === category.id }">
            {{ category.name }}
          </el-button>
          <template #dropdown>
            <el-dropdown-menu class="submenu">
              <el-dropdown-item v-for="tag in categoryTags[category.id]" 
                              :key="tag.id" 
                              class="submenu-item"
                              @click="getCourseByTagId(tag)">
                {{ tag.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <!-- 课程列表标题 -->
      <h2 class="section-title">{{ title }}</h2>

      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        
        <div class="sort-box">
          <el-radio-group v-model="queryParams.sort" @change="changeSort" size="small">
            <el-radio-button label="newest">最新</el-radio-button>
            <el-radio-button label="hotest">最热</el-radio-button>
            <el-radio-button label="price">价格</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 课程列表 -->
      <div class="course-section">
        <div class="course-list">
          <div v-for="course in courseList" :key="course.id" class="course-item" @click="goToVideo(course.id)">
            <div class="course-image">
              <el-image :src="course.cover" fit="cover"></el-image>
              <div class="play-icon">
                <el-icon><video-play /></el-icon>
              </div>
              <div class="price-tag" v-if="course.price > 0">¥{{ formatPrice(course.price) }}</div>
              <div class="price-tag free" v-else>免费</div>
            </div>
            <div class="course-content">
              <h3 class="course-title">{{ course.title }}</h3>
              <p class="course-description">{{ course.summary }}</p>
              <div class="course-meta">
                <div class="meta-left">
                  <span class="author">{{ course.username }}</span>
                  <span class="views">{{ course.watchNums }} 播放</span>
                </div>
                <div class="meta-right">
                  <span class="time">{{ new Date(course.createTime).toLocaleDateString() }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="empty-hint" v-if="courseList.length === 0">
          <p>暂无相关课程</p>
        </div>
      </div>
    </el-main>

    <!-- 个人信息对话框 -->
    <el-dialog v-model="info" title="个人信息" width="500px">
      <el-form :model="form1" label-width="80px">
        <el-form-item label="头像">
          <div style="display: flex; align-items: center;">
            <el-avatar :src="form1.avatar" :icon="UserFilled" style="margin-right: 10px;" />
            <el-upload :on-change="handleAvatarChange" :auto-upload="false" :show-file-list="false">
              <el-button size="small" type="primary">修改头像</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form1.username" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="info = false">取消</el-button>
          <el-button type="primary" @click="saveInfo">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="password" title="修改密码" width="500px">
      <el-form :model="form2" label-width="80px">
        <el-form-item label="旧密码">
          <el-input type="password" v-model="form2.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" v-model="form2.newPassword" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="form2.surePassword" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="password = false">取消</el-button>
          <el-button type="primary" @click="savePassword">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<style lang="scss" scoped>
.home-container {
  background: #fff;
  min-height: 100vh;

  /* 导航栏样式 */
  .header {
    height: 70px !important;
    background: #ffffff;
    border-bottom: 1px solid #ebeef5;
  }

  .nav-container {
    max-width: 1440px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    height: 100%;
    padding: 0 24px;
  }

  .logo {
    font-size: 24px;
    font-weight: 600;
    margin-right: 48px;
    color: #303133;

    .blue {
      color: #409eff;
    }
  }

  .el-menu--horizontal {
    background: transparent !important;
    border-bottom: none !important;
    flex: 1;
  }

  .el-menu-item {
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    padding: 0 28px;
    color: #606266;
    transition: color 0.3s;
  }

  .el-menu-item.is-active {
    color: #409eff !important;
    border-bottom: 2px solid #409eff;
  }

  .search-box {
    margin-left: auto;
    margin-right: 24px;
  }

  .search-box .el-input {
    --el-input-border-radius: 20px;
    --el-input-bg-color: #f5f7fa;
  }

  .user-panel .el-button {
    border-radius: 20px;
    padding: 10px 24px;
    background: #409eff;
    color: white;
  }
}

.page-header {
  text-align: center;
  padding: 40px 0;
  margin-bottom: 30px;
  background: #409eff;
  border-radius: 8px;
  color: white;

  .page-title {
    font-size: 32px;
    margin-bottom: 10px;
  }

  .page-description {
    font-size: 16px;
    opacity: 0.9;
  }
}

.category-container {
  display: flex;
  gap: 8px;
  margin: 0 auto 15px;
  padding: 15px 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  justify-content: flex-start;
  max-width: 1200px;
  
  .category-tag {
    padding: 8px 16px;
    border-radius: 16px;
    font-size: 14px;
    transition: all 0.3s;
    min-width: 90px;
    text-align: center;
    border: 1px solid #abadb2b3;
    background: #ffffff;
    height: auto !important;
    width: auto !important;
    color: #606266;
    
    &:hover, &.active {
      background: #409eff;
      color: white;
      transform: translateY(-2px);
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    }
  }
}

.section-title {
  position: relative;
  color: #303133;
  font-size: 25px;
  display: flex;
  align-items: center;
  margin-bottom: 15px;

  &::before {
    content: '';
    width: 4px;
    height: 25px;
    background: linear-gradient(180deg, #409eff, #79bbff);
    border-radius: 2px;
    margin-right: 15px;
  }
}

.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .search-box {
    .search-input {
      width: 300px;
    }
  }

  .sort-box {
    .el-radio-button__inner {
      padding: 8px 15px;
    }
  }
}

.course-section {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .course-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .course-item {
    display: flex;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
    cursor: pointer;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);

      .play-icon {
        transform: translate(-50%, -50%) scale(1.1);
      }
    }

    .course-image {
      width: 240px;
      height: 160px;
      position: relative;
      flex-shrink: 0;
      
      .el-image {
        width: 100%;
        height: 100%;
      }

      .play-icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 50px;
        height: 50px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        transition: all 0.3s;
        font-size: 24px;
      }
      
      .price-tag {
        position: absolute;
        top: 10px;
        right: 10px;
        background: rgba(245, 108, 108, 0.9);
        color: white;
        padding: 3px 8px;
        border-radius: 4px;
        font-weight: bold;
        
        &.free {
          background: rgba(103, 194, 58, 0.9);
        }
      }
    }
    
    .course-content {
      flex: 1;
      padding: 15px;
      display: flex;
      flex-direction: column;
      
      .course-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .course-description {
        color: #666;
        font-size: 14px;
        margin-bottom: 15px;
        flex: 1;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .course-meta {
        display: flex;
        justify-content: space-between;
        color: #999;
        font-size: 12px;
        
        .meta-left {
          display: flex;
          align-items: center;
          gap: 15px;
        }
      }
    }
  }
}

.empty-hint {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

/* User Menu Styles */
.user-menu {
  .menu-item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    
    i {
      margin-right: 8px;
      font-size: 16px;
    }
    
    &:hover {
      background: #f0f2f5;
      color: #409EFF;
    }
    
    &.logout {
      color: #F56C6C;
      
      &:hover {
        background: #fef0f0;
      }
    }
  }
}
</style> 